package com.example.friend.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.core.constants.Constants;
import com.example.core.entity.PageDataInfo;
import com.example.core.enums.ExamListType;
import com.example.core.enums.ResultCode;
import com.example.core.utils.ThreadLocalUtil;
import com.example.friend.component.manager.ExamCacheManager;
import com.example.friend.entity.DO.ExamDO;
import com.example.friend.entity.DO.UserExamDO;
import com.example.friend.entity.DTO.ExamQueryDTO;
import com.example.friend.entity.VO.ExamVO;
import com.example.friend.mapper.UserExamMapper;
import com.example.friend.service.IExamService;
import com.example.friend.service.IUserExamService;
import com.example.security.exception.ServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private IExamService examService;
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private ExamCacheManager examCacheManager;


    @Override
    public int signUp(String token, Long examId) {
        // 校验参数
        ExamDO exam = examService.getExam(examId);
        if (exam == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        this.checkExamTime(exam.getStartTime());
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        LambdaQueryWrapper<UserExamDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserExamDO::getExamId, examId).
                eq(UserExamDO::getUserId, userId);
        UserExamDO exists = userExamMapper.selectOne(wrapper);
        if (exists != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        // 向数据库、redis中存储数据
        examCacheManager.addUserExamCache(userId, examId);
        UserExamDO userExamDO = new UserExamDO();
        userExamDO.setExamId(examId);
        userExamDO.setUserId(userId);
        return userExamMapper.insert(userExamDO);
    }


    @Override
    public PageDataInfo<ExamVO> list(ExamQueryDTO examQueryDTO) {
        // 先查询缓存，没有在查询数据库
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            // 从数据库中查询 并同步到redis
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return PageDataInfo.empty();
        }
        return PageDataInfo.success(examVOList, total);
    }

    /**
     * 校验竞赛是否已经开始
     * @param startTime startTime
     */
    private void checkExamTime(LocalDateTime startTime) {
        if(startTime.isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
    }

}
